import { refreshEx } from '../../services/crud'

var moment = require('moment');
moment.defaultFormat = "YYYY-MM-DD HH:mm:ss";
import io from 'socket.io-client'
function translate(a) {
  if (a.params) {
    a.ip = a.params.ip
    a.business_id = a.params.business_id
    a.reason = a.params.reason
  }
  if(a.alarm_name === '离线'){
    a.alarm_name = '设备断网'
  }
}
function sortAlarm(a, b) {
  return b.time - a.time
}
let msgClient
function initMsgChannel(dispatch) {
  console.log("hello-------------------------------11")
  msgClient = io('', { transports: ['websocket'], path: "/ws/" })
  msgClient.on('connect', () => {
    console.log('+++ io connected! ++++', msgClient.id)
    dispatch('onUID', msgClient.id)
    msgClient.on("alarm", (data) => {
      console.log("------------------data------------", data)
      dispatch('alarm', data)
    })
    msgClient.on("alarmRefresh", (data) => {
      console.log("---------------alarmrefreshed-------------", data)
      dispatch('refreshActiveAlarm')
    })
  })

  return msgClient
  //console.log(msgClient,getToken,io)
}
export default {
  namespaced: true,
  state: {
    activeAlarms: [],
    cache: {},
    sid: '',
  },
  getters: {
    activeAlarms: state => {
      return state.activeAlarms
    },
    SID: state => {
      return state.sid
    }
  },
  mutations: {
    setUID(state, id) {
      state.sid = id
    },
    setAlarms(state, { result }) {
      state.cache = {}
      //console.log("------result", result)
      let alarms = result
      /*const tc = rootState.station.thingCache*/
      if (alarms) {
        /*alarms.forEach(a=>{
          translate(a,tc)
       })*/
        alarms = alarms.map(a=>{
          if(a.alarm_obj){
            let aobj = JSON.parse(a.alarm_obj)
            if(aobj){
              if(aobj.thing_name == "" || aobj.thing_name == undefined){
                aobj.thing_name = a.thing_name;
              }
            }
            return aobj;
          }
          return a
        })
        state.activeAlarms = alarms.sort(sortAlarm)
        if (alarms) {
          let i = 0
          alarms.forEach(a => {
            a.index = i
            i++
            state.cache[a.alarm_id + a.m_id + a.mindex + a.t_id] = a
            translate(a)
            //a.ip = a.params
            a.alarm_time = moment.unix(a.time).format()
          });
        }
      }
      else {
        state.activeAlarms = []
      }
     
      //console.log("******************", state.activeAlarms)

    },
    setAlarm(state, {result,dispatch}) {
      let alarm = result
      if (alarm) {
        const id = alarm.alarm_id + alarm.mindex + alarm.t_id
        alarm.akey = id
        const oldAlarm = state.cache[id]
        if (alarm.flag == "BEGIN") {

          translate(alarm)
          if (oldAlarm) {
            let index = state.activeAlarms.findIndex(a=>{
              return a.akey == id
            })
            if(index >= 0 && alarm.thing_name != "" && alarm.thing_name != undefined){
              state.activeAlarms[index] = alarm
            }else{
              console.log("error-------------alarm-----------",alarm,state.activeAlarms)
            }
            return;
          }
          
          state.cache[id] = alarm

          //alarm.index = state.activeAlarms.length
          alarm.alarm_time = moment.unix(alarm.time). format()
          state.activeAlarms.unshift(alarm)
        }
        else {
          if (!oldAlarm) {
            console.log("error--------clear----------------",alarm,state.activeAlarms)
            return
          }
          delete state.cache[id]
          let index = state.activeAlarms.findIndex((a)=>{
            return a.akey === id
          })
          if(index >= 0){
            state.activeAlarms.splice(index,1)
          }else{
            console.log("error--------clear--------222--------")
          }

        }
      }
      
    }
  },
  actions: {
    refreshActiveAlarm({ commit, rootState, dispatch }) {
      if (!msgClient) {
        initMsgChannel(dispatch)
      }
      return refreshEx(commit, 'setAlarms', 'alarm/real',rootState,dispatch)
    },
    alarm({ commit,dispatch }, alarm) {
      commit("setAlarm", {result:alarm,dispatch})
    },
    onUID({ commit }, id) {
      commit('setUID', id)
    }
  }
}